package com.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.domain.dto.MenuDTO;
import com.crm.domain.vo.MenuVO;
import com.crm.mapper.MenuMapper;
import com.crm.service.MenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
@RequiredArgsConstructor
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuDTO> implements MenuService {

    private final MenuMapper menuMapper;

    /**
     * 获取菜单树
     * @return 菜单树
     */
    @Override
    public List<MenuVO> getMenuTree() {

        List<MenuDTO> menuList = menuMapper.selectList(new QueryWrapper<>());

        List<MenuVO> menuTree = buildMenuTree(menuList, 0L);

        return menuTree;
    }

    /**
     * 递归构建菜单树
     * @param menuList 菜单列表
     * @param parentId 父菜单ID
     * @return 菜单树
     */
    private List<MenuVO> buildMenuTree(List<MenuDTO> menuList, Long parentId) {
        List<MenuVO> tree = new ArrayList<>();
        for (MenuDTO menu : menuList) {
            if (menu.getParentId().equals(parentId)) {
                MenuVO menuVO = new MenuVO();
                menuVO.setMenuId(menu.getMenuId());
                menuVO.setMenuName(menu.getMenuName());
                menuVO.setParentId(menu.getParentId());
                menuVO.setOrderNum(menu.getOrderNum());
                menuVO.setPath(menu.getPath());
                menuVO.setComponent(menu.getComponent());
                menuVO.setIsFrame(menu.getIsFrame());
                menuVO.setIsCache(menu.getIsCache());
                menuVO.setMenuType(menu.getMenuType());
                menuVO.setVisible(menu.getVisible());
                menuVO.setStatus(menu.getStatus());
                menuVO.setPerms(menu.getPerms());
                menuVO.setIcon(menu.getIcon());
                menuVO.setCreateBy(menu.getCreateBy());
                menuVO.setCreateTime(menu.getCreateTime());
                menuVO.setUpdateBy(menu.getUpdateBy());
                menuVO.setUpdateTime(menu.getUpdateTime());
                menuVO.setRemark(menu.getRemark());

                List<MenuVO> children = buildMenuTree(menuList, menu.getMenuId());
                menuVO.setChildren(children);

                tree.add(menuVO);
            }
        }
        return tree;
    }
}
